package Demo01;

public class Main {

}

class Solution {
    public static void main(String[] args) {
        System.out.println(longestCommonSubsequence("abcde", "zbcexy"));
    }

    public static int longestCommonSubsequence(String text1, String text2) {
        int[][] dp = new int[text1.length() + 1][text2.length() + 1];
        for (int i = 1; i <= text1.length(); i++) {
            for (int j = 1; j <= text2.length(); j++) {
                if (text1.charAt(i-1) == text2.charAt(j-1)) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        return dp[text1.length()][text2.length()];
    }

    private static int f2(String s1, String s2, int i1, int i2, int[][] dp) {
        if (i1 < 0 || i2 < 0) {
            return 0;
        }
        if (dp[i1][i2] != -1) {
            return dp[i1][i2];
        }
        int l = 0;
        if (s1.charAt(i1) == s2.charAt(i2)) {
            l = f2(s1, s2, i1 - 1, i2 - 1, dp) + 1;
        } else {
            l = Math.max(f2(s1, s2, i1 - 1, i2, dp), f2(s1, s2, i1, i2 - 1, dp));
        }
        dp[i1][i2] = l;
        return l;
    }

    public static int longestCommonSubsequence1(String text1, String text2) {
        int i1 = text1.length() - 1;
        int i2 = text2.length() - 1;
        int[][] dp = new int[text1.length()][text2.length()];
        for (int i = 0; i < text1.length(); i++) {
            for (int j = 0; j < text2.length(); j++) {
                dp[i][j] = -1;
            }
        }
        return f2(text1, text2, i1, i2, dp);
    }


    private static int f1(String s1, String s2, int i1, int i2) {
        if (i1 < 0 || i2 < 0) {
            return 0;
        }
        int l = 0;
        if (s1.charAt(i1) == s2.charAt(i2)) {
            l = f1(s1, s2, i1 - 1, i2 - 1) + 1;
        } else {
            l = Math.max(Math.max(f1(s1, s2, i1 - 1, i2), f1(s1, s2, i1, i2 - 1)), f1(s1, s2, i1 - 1, i2 - 1));
        }
        return l;
    }


}